<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getArchiveReviewList, getArchiveDetail, reviewArchive } from '@/api/archive'

const columns = [
  { title: '员工编号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '姓名', dataIndex: 'name', key: 'name', width: 100 },
  { title: '所属机构', dataIndex: 'org', key: 'org', width: 150 },
  { title: '职位', dataIndex: 'position', key: 'position', width: 120 },
  { title: '登记人', dataIndex: 'registrant', key: 'registrant', width: 100 },
  { title: '登记时间', dataIndex: 'registerTime', key: 'registerTime', width: 180 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
]

const dataSource = ref([])
const loading = ref(false)
const reviewRecord = ref(null)
const reviewVisible = ref(false)
const reviewForm = ref({
  result: null,
  comment: '',
})

// 详情弹窗相关
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref({})

// 获取待复核档案列表
const fetchReviewList = async () => {
  loading.value = true
  try {
    const response = await getArchiveReviewList()

    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id,
      }))
    } else {
      dataSource.value = []
    }
  } catch (error) {
    console.error('获取待复核档案列表失败:', error)
    message.error('获取数据失败')
    dataSource.value = []
  } finally {
    loading.value = false
  }
}

const handleReview = (record) => {
  reviewRecord.value = record
  reviewVisible.value = true
  reviewForm.value = { result: null, comment: '' }
}

// 获取档案详情
const fetchArchiveDetail = async (id) => {
  detailLoading.value = true
  try {
    const response = await getArchiveDetail(id)
    if (response) {
      detailData.value = response
    } else {
      message.error('获取详情失败')
      detailData.value = {}
    }
  } catch (error) {
    console.error('获取档案详情失败:', error)
    message.error('获取详情失败')
    detailData.value = {}
  } finally {
    detailLoading.value = false
  }
}

// 打开详情弹窗
const handleViewDetail = async (record) => {
  detailVisible.value = true
  await fetchArchiveDetail(record.id)
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  detailData.value = {}
}

const handleReviewSubmit = async () => {
  if (!reviewForm.value.result) {
    message.warning('请选择复核结果')
    return
  }
  if (reviewForm.value.result === '不通过' && !reviewForm.value.comment) {
    message.warning('请填写不通过原因')
    return
  }

  try {
    const response = await reviewArchive(reviewRecord.value.id, {
      result: reviewForm.value.result,
      comment: reviewForm.value.comment || '',
    })

    if (response && response.status) {
      message.success(`复核${reviewForm.value.result}，操作成功`)
      reviewVisible.value = false

      // 更新状态
      const index = dataSource.value.findIndex((item) => item.key === reviewRecord.value.key)
      if (index !== -1) {
        dataSource.value[index].status = response.status
      }

      // 刷新列表
      await fetchReviewList()
    } else {
      message.error('复核失败，请稍后重试')
    }
  } catch (error) {
    console.error('复核档案失败:', error)
    message.error('复核失败，请稍后重试')
  }
}

onMounted(() => {
  fetchReviewList()
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">人力资源档案复核</h1>
      <p class="page-desc">对登记的档案信息进行审核确认，确保信息完整性和准确性</p>
    </div>

    <div class="page-content">
      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="{ pageSize: 10 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '待复核'
                    ? 'orange'
                    : record.status === '已生效'
                      ? 'green'
                      : 'red'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleReview(record)">复核</a-button>
              <a-button type="link" size="small" @click="handleViewDetail(record)"
                >查看详情</a-button
              >
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:open="reviewVisible" title="档案复核" width="600px" @ok="handleReviewSubmit">
      <div class="review-info">
        <p><strong>员工编号：</strong>{{ reviewRecord?.code }}</p>
        <p><strong>姓名：</strong>{{ reviewRecord?.name }}</p>
        <p><strong>所属机构：</strong>{{ reviewRecord?.org }}</p>
        <p><strong>职位：</strong>{{ reviewRecord?.position }}</p>
      </div>
      <div class="review-form">
        <div class="form-item">
          <label>复核结果 <span style="color: red">*</span></label>
          <a-radio-group v-model:value="reviewForm.result">
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </div>
        <div class="form-item">
          <label>复核意见</label>
          <a-input
            v-model:value="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入复核意见（不通过时必填）"
          />
        </div>
      </div>
    </a-modal>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="档案详情"
      width="800px"
      :footer="null"
      @cancel="handleCloseDetail"
    >
      <a-spin :spinning="detailLoading">
        <div v-if="!detailLoading && Object.keys(detailData).length > 0" class="detail-content">
          <a-card title="基本信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="员工编号">{{ detailData.code }}</a-descriptions-item>
              <a-descriptions-item label="姓名">{{ detailData.name }}</a-descriptions-item>
              <a-descriptions-item label="性别">{{ detailData.gender }}</a-descriptions-item>
              <a-descriptions-item label="身份证号">{{ detailData.idCard }}</a-descriptions-item>
              <a-descriptions-item label="出生日期">{{ detailData.birthDate }}</a-descriptions-item>
              <a-descriptions-item label="民族">{{ detailData.ethnicity }}</a-descriptions-item>
              <a-descriptions-item label="政治面貌">{{
                detailData.politicalStatus
              }}</a-descriptions-item>
              <a-descriptions-item label="婚姻状况">{{
                detailData.maritalStatus
              }}</a-descriptions-item>
              <a-descriptions-item label="手机号码">{{ detailData.phone }}</a-descriptions-item>
              <a-descriptions-item label="邮箱">{{ detailData.email }}</a-descriptions-item>
              <a-descriptions-item label="紧急联系人">{{
                detailData.emergencyContact
              }}</a-descriptions-item>
              <a-descriptions-item label="紧急联系人电话">{{
                detailData.emergencyPhone
              }}</a-descriptions-item>
            </a-descriptions>
          </a-card>

          <a-card title="工作信息" class="detail-section" :bordered="false">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="所属机构">{{
                detailData.organization
              }}</a-descriptions-item>
              <a-descriptions-item label="职位">{{ detailData.position }}</a-descriptions-item>
              <a-descriptions-item label="入职日期">{{ detailData.joinDate }}</a-descriptions-item>
              <a-descriptions-item label="试用期">{{
                detailData.probationPeriod
              }}</a-descriptions-item>
              <a-descriptions-item label="合同期限">{{
                detailData.contractPeriod
              }}</a-descriptions-item>
              <a-descriptions-item label="直接上级">{{
                detailData.supervisor
              }}</a-descriptions-item>
              <a-descriptions-item label="工作地点">{{
                detailData.workLocation
              }}</a-descriptions-item>
              <a-descriptions-item label="状态">
                <span
                  :class="['status-badge', detailData.status === '在职' ? 'active' : 'inactive']"
                >
                  {{ detailData.status }}
                </span>
              </a-descriptions-item>
              <a-descriptions-item label="工资卡开户行">{{
                detailData.bankName
              }}</a-descriptions-item>
              <a-descriptions-item label="银行卡号">{{
                detailData.bankAccount
              }}</a-descriptions-item>
            </a-descriptions>
          </a-card>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.review-info {
  background: #f5f5f7;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.review-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #1d1d1f;
}

.review-form {
  margin-top: 16px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}

.detail-content {
  padding: 8px 0;
}

.detail-section {
  margin-bottom: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.detail-section :deep(.ant-card-head) {
  background: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  padding: 16px 24px;
}

.detail-section :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.detail-section :deep(.ant-card-body) {
  padding: 24px;
}

.detail-section :deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background: #f5f5f5;
}

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.status-badge.inactive {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}
</style>
